package com.hzjq.core.worker

import com.hzjq.core.BlastDelegate
import com.hzjq.core.ErrorCode
import com.hzjq.core.bean.CapEntity
import com.hzjq.core.callback.Callback
import com.hzjq.core.massage.DataMessageBean
import com.hzjq.core.receive.Receiver
import com.hzjq.core.receive.Receives
import com.hzjq.core.work.Work


/**
 * 读雷管数据
 */
class ReadCapWork : Work<MutableList<CapEntity>> {

    private var progress = 0

    private var count = 0

    private var caps: MutableList<CapEntity>? = null

    private var oldProgress = 0

    private var mErrorReadWork: ErrorReadWork? = null

    private var currentCapCount = 0

    private var totalCapCount = 0


    constructor(callback: Callback<MutableList<CapEntity>>?) : super(callback)

    override fun doWork(vararg args: Any) {
        if (args.isNotEmpty()) {
            count = args[0] as Int
            totalCapCount = args[1] as Int
            if (args.size >= 3) {
                oldProgress = args[1] as Int
                progress = oldProgress
                caps = args[2] as MutableList<CapEntity>
            } else {
                oldProgress = 40
            }

            if (args[args.size - 1] is ErrorReadWork) {
                mErrorReadWork = args[args.size - 1] as ErrorReadWork
                mErrorReadWork?.cancel()
            }

            BlastDelegate.getDelegate().post(Runnable {
                onProgressChanged(progress, "正在读取雷管信息")
            })

            var position = count
            if(count > totalCapCount) {
                position = count - 16
            }

            Receives.getInstance()
                .registerReceiver(
                    BlastDelegate.getDelegate().getAssemblyCmdLoader().getReadCapCmd(position),
                    object : Receiver {
                        override fun convert(msg: String): Any {
                            if (msg.length > 40) {
                                checkCapRetry(msg)
                                return BlastDelegate.getDelegate().getParseLoader()
                                    .parseCap(msg)
                            }
                            return msg
                        }

                        override fun onSuccess(msg: Any) {
                            if (msg is MutableList<*>) {
                                val parseCaps = msg as MutableList<CapEntity>
                                checkMaxLimitCap(parseCaps)
                            } else {
                                onProgressChanged(100, "读取雷管信息失败")
                                callback?.onError(ErrorCode.getErrorResult(-15))
                                onDestroy()
                            }
                        }

                        override fun failed() {
                            onProgressChanged(100, "读取雷管信息失败")
                            callback?.onError(ErrorCode.getErrorResult(-16))
                            onDestroy()
                        }

                    })
            val msg = DataMessageBean(
                BlastDelegate.getDelegate().getAssemblyCmdLoader().getReadCapCmd(count).cmd
            )
            BlastDelegate.getDelegate().getCmdExeLoader().exePollResultCmd(msg.assembly(), callback)
        }
    }


    private fun checkCapRetry(msg: String) {
        val total = Integer.valueOf(msg.substring(16, 20), 16)
        if (total > BlastDelegate.getDelegate().getMaxSupportCapCount()) {
            if (mErrorReadWork != null) {
                mErrorReadWork?.doWork(total)
            } else {
                callback?.onError(ErrorCode.getErrorResult(113))
            }
        } else {
            if (count < total) {
                retry(count + 16, totalCapCount)
            }
        }
    }

    private fun checkMaxLimitCap(caps: MutableList<CapEntity>) {
        caps.forEach {
            val errorCap = mErrorReadWork?.checkCapError(it)
            if (errorCap != null) {
                mErrorReadWork?.doWork(it.total)
                return
            }
        }

        if (caps[0].total > BlastDelegate.getDelegate().getMaxSupportCapCount()) {
            if (mErrorReadWork != null) {
                mErrorReadWork?.doWork(caps[0].total)
            } else {
                callback?.onError(ErrorCode.getErrorResult(113))
            }
        } else if (currentCapCount + caps.size >= totalCapCount) {
            onProgressChanged(100, "已读取全部雷管信息")
            checkNotMatchCap(caps)
            onDestroy()
        } else {
            currentCapCount += caps.size
            callback?.onResult(caps)
            progress =
                ((currentCapCount + 1) * ((100.0f - oldProgress.toFloat()) / caps[0].total.toFloat())).toInt() + oldProgress
        }

    }

    private fun checkNotMatchCap(caps: MutableList<CapEntity>) {
        caps[caps.size - 1].isScanEnd = true
        callback?.onResult(caps)
    }

    override fun cancel() {
        Receives.getInstance()
            .unRegisterReceiver(
                BlastDelegate.getDelegate().getAssemblyCmdLoader().getReadCapCmd(count)
            )
    }

}